package com.fengye.security.captcha.authentication.security.beans;

import com.fengye.security.captcha.authentication.security.exception.VerificationCodeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 *
 * @author sky
 * @date 2021年06月01日 11:18 上午
 */
@Component
@Slf4j
public class MyAuthenticationProvider extends DaoAuthenticationProvider {

    MyAuthenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder){
        this.setUserDetailsService(userDetailsService);
        this.setPasswordEncoder(passwordEncoder);
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken) throws AuthenticationException {
        // 实现图形验证码的校验逻辑
        MyWebAuthenticationDetails details = (MyWebAuthenticationDetails) usernamePasswordAuthenticationToken.getDetails();
        String imageCode = details.getImageCode();
        String savedImageCode = details.getSavedImageCode();
        // 校验
        if (StringUtils.hasText(imageCode)&& StringUtils.hasText(savedImageCode)&& imageCode.equals(savedImageCode)){
            log.info("校验通过");
        }else{
            throw new VerificationCodeException();
        }

        // 调用父类的方法完成密码校验
        super.additionalAuthenticationChecks(userDetails, usernamePasswordAuthenticationToken);
    }
}
